package com.xbjtech.controller;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.xbjtech.model.vo.QueryVo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.excel.poi.util.PoiAnalyticalData;
import com.excel.poi.util.PoiUtil;
import com.github.pagehelper.PageInfo;
import com.xbjtech.model.Order;
import com.xbjtech.model.Seller;
import com.xbjtech.model.beans.Result;
import com.xbjtech.model.excel.OrderExcelIn;
import com.xbjtech.model.excel.OrderExcelOut;
import com.xbjtech.realm.CustomRealm;
import com.xbjtech.service.OrderService;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {
	
	@Autowired
	SellerController sellerController;
	
	@Autowired
	OrderService orderService;

	@RequestMapping("/list")
	public String list() {
		return "order/list";
	}
	
	
	@GetMapping("/data")
	@ResponseBody
	public Map<String, Object> data(
			QueryVo vo,
			@RequestParam(value = "page", required = false, defaultValue = "1")
			Integer page,
			@RequestParam(value = "rows", required = false, defaultValue = "10")
			Integer rows
			) {
		System.out.println(vo);
		Example ex = new Example(Order.class);
		Example.Criteria criteria = ex.createCriteria();
		if (null != vo.getAjOrderId() && vo.getAjOrderId().length() != 0) {
			criteria.andEqualTo("ajOrderId", vo.getAjOrderId());
		}
		if (null != vo.getSellerId()) {
			criteria.andEqualTo("sellerId", vo.getSellerId());
		}
		if (null != vo.getBuyerName() && vo.getBuyerName().length() != 0) {

			//  buyer_name like concat('%', #{value}, '%')  用这种方式
			//  buyer_name like '%${value}%'
			criteria.andLike("buyerName", "%" + vo.getBuyerName() + "%");
		}
		if (null != vo.getBeginDate()) {
			criteria.andGreaterThanOrEqualTo("createTime", vo.getBeginDate());
		}
		if (null != vo.getEndDate()) {
			criteria.andLessThan("createTime", new Date(vo.getEndDate().getTime() + (24 * 60 * 60 * 1000)));
		}

		PageInfo<Order> orders = orderService.selectByExamplePage(page, rows, ex);
		Map<String, Object> map = new HashMap<>();
		map.put("total", orders.getTotal());
		map.put("rows", orders.getList());
		return map;
	}
	
	@PostMapping(value = "/save", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result save(@Validated Order order, Errors errors) {
		// 服务器端校验
		// errors还需要处理一下
		try {
			if (null == order.getId()) {
				order.setState(0);
				order.setCreateTime(new Date());
				orderService.insertWithoutPrimaryKey(order);
			} else {
				orderService.updateByPrimaryKey(order);
			}
			return Result.success();
		} catch (Exception e) {
		}
		return Result.fail();
	}
	
	@Autowired
	CustomRealm customRealm;
	
	@GetMapping("/del")
	@ResponseBody
	public Result del(
			@RequestParam(value = "id", required = true)
			Integer id) {
		try {
			orderService.deleteByPrimaryKey(id);
			return Result.success();
		} catch (Exception e) {
		}
		return Result.fail();
	}
	
	@GetMapping("/excelout")
	public void excelout(HttpServletResponse response) {
		// excel jsp 视图
		// 先查List<Order>
		
		List<Order> list = orderService.selectAll();
		
		String json = sellerController.getSellers();
		List<Seller> sellers = JSON.parseObject(json, new TypeReference<List<Seller>>(){});
		
		List<Object> excelData = new LinkedList<>();
		for (Order order : list) {
			OrderExcelOut out = new OrderExcelOut();
			out.setAjOrderId(order.getAjOrderId());
			out.setBuyerCar(order.getBuyerCar());
			out.setBuyerMobile(order.getBuyerMobile());
			out.setBuyerName(order.getBuyerName());
			out.setPrice(order.getPrice().toString());
			for (Seller seller : sellers) {
				if (seller.getId().compareTo(order.getSellerId()) == 0) {
					out.setSellerName(seller.getName());
					break;
				}
			}
			switch(order.getState()) {
				case 0: out.setState("待派单");break;
				case 1: out.setState("待安装");break;
				case 2: out.setState("已核销");break;
				case 3: out.setState("订单结束");break;
				default: out.setState("未知");break;
			}
			out.setAddress(order.getBuyerAddress());
			excelData.add(out);
		}
		try {
			XSSFWorkbook xssfWorkbook = PoiUtil.createXSSFWorkbook("订单", OrderExcelOut.class, excelData);
			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.addHeader("Content-Disposition", "attachement;filename=" + URLEncoder.encode("订单.xlsx", "UTF-8"));
			//response.addHeader("Content-Disposition", "attachement;filename=" + new String("订单.xlsx".getBytes("UTF-8"), "ISO-8859-1"));
			xssfWorkbook.write(outputStream);
		} catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
			log.error("excel创建失败");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@PostMapping("/excelin")
	@ResponseBody
	public Result excelin(
			@RequestParam(value = "sellerId", required = true)
			Integer sellerId,
			@RequestParam(value = "excel", required = true)
			MultipartFile excel
			) {
		System.out.println("sellerId=>" + sellerId);
		System.out.println("excel=>" + excel);
		//
		InputStream inputStream;
		try {
			inputStream = excel.getInputStream();
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
			
			// 解析
			List<Object> excelData = PoiAnalyticalData.analyticPoiExcel(xssfWorkbook, OrderExcelIn.class);
			List<Order> orders = new LinkedList<>();
			for (Object o : excelData) {
				OrderExcelIn oei = (OrderExcelIn) o;
				Order order = new Order();
				order.setAjOrderId(oei.getAjOrderId());
				order.setState(0);
				order.setBuyerAddress(oei.getAddress());
				order.setBuyerCar(oei.getBuyerCar());
				order.setSellerId(sellerId);
				order.setBuyerMobile(oei.getBuyerMobile());
				order.setBuyerName(oei.getBuyerName());
				order.setBuyerProduct(oei.getBuyerProduct());
				order.setPrice(new BigDecimal(oei.getPrice()));
				orders.add(order);
			}
			orderService.insertOrders(orders);
			return Result.success();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return Result.fail();
	}
}
